package cn.itcast.core.service.product;

import cn.itcast.common.page.Pagination;
import cn.itcast.core.bean.product.Brand;
import cn.itcast.core.dao.product.BrandDao;
import cn.itcast.core.query.product.BrandQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public 	class BrandService  {
	@Resource
	private BrandDao brandDao;

	// 加入只读事务注解
	@Transactional(readOnly = true)
	public Brand findBrandByid(Integer id) {
		return brandDao.findBrandByid(id);
	}

	@Transactional(readOnly = true)
	public List<Brand> getBrandList(BrandQuery brandQuery) {
		return brandDao.getBrandList(brandQuery);
	}

	@Transactional(readOnly = true)
	public Pagination getBrandListWithPage(Brand brand, Integer pageNo){
		// 1.起始页
		// 每页显示数 int pageNo, int pageSize, int totalCount
		Pagination pagination = new Pagination();
		// 查询map
		Map queryParams = new HashMap();
		queryParams.put("isDisplay",brand.getIsDisplay());
		queryParams.put("name",brand.getName());

		// 设置分页参数，每页显示5条数据。
		Integer pageSize = 5;
		// todo 此处校验逻辑应该交给前台！
		// 不能小于1
		pageNo = Pagination.cpn(pageNo);
		Integer brandCount = brandDao.getBrandCount(brand);
		// 不能超过最大页数
		pageNo = pageNo*pageSize < brandCount ? pageNo: (int)Math.ceil((double)brandCount/pageSize);
		queryParams.put("startPage", (pageNo - 1) * pageSize);
		queryParams.put("pageSize", pageSize);

		// 放入数据
		pagination.setList(brandDao.getBrandListWithPage(queryParams));
		pagination.setPageSize(pageSize);
		pagination.setTotalCount(brandCount);
		pagination.setPageNo(pageNo);

		return pagination;
	}

	public void addBrand(Brand brand){
		brandDao.addBrand(brand);
	}

	public void deleteBrand(Integer id){
		brandDao.deleteBrand(id);
	}


	public void batchDeleteBrand(String ids){
//		if(!ids.contains(",")){
//			brandDao.deleteBrand(Integer.valueOf(ids));
//		}else {
//			brandDao.batchDeleteBrand(ids.split(","));
//		}

		brandDao.batchDeleteBrand(ids.split(","));
	}

	public void saveBrand(Brand brand){
		brandDao.saveBrand(brand);
	}
}
